#include <allegro.h>
#include <stdlib.h>
#include "libraries/pthread/pthread.h"

#include "Video.h"
#include "Common.h"

BITMAP* buffer;
BITMAP* videoPage[3];
int videoMode;
int videoPageId;

pthread_mutex_t videoMutex;

void SetVideoMode(int vMode)
{
    int i;

    if (videoMode == vMode)
        return;

    pthread_mutex_lock(&videoMutex);

    videoMode = vMode;

    for (i = 0; i < 3; i++)
    {
        if (videoPage[i])
            destroy_bitmap(videoPage[i]);
        videoPage[i] = NULL;
    }
    videoPageId = 0;

    switch (videoMode)
    {
        case VIDEO_MODE_PAGE_FLIPPING:
            videoPage[0] = create_video_bitmap(SCREEN_W, SCREEN_H);
            videoPage[1] = create_video_bitmap(SCREEN_W, SCREEN_H);
            buffer = videoPage[0];
            break;
        case VIDEO_MODE_DOUBLE_BUFFERING:
            videoPage[0] = create_bitmap(SCREEN_W, SCREEN_H);
            buffer = videoPage[0];
            break;
        case VIDEO_MODE_NO_BUFFERING:
            buffer = screen;
            break;
    }

    pthread_mutex_unlock(&videoMutex);
}

void DisplayScreen()
{
    static int lastTimeCheck = 0;

    pthread_mutex_lock(&videoMutex);

    switch (videoMode)
    {
        case VIDEO_MODE_PAGE_FLIPPING:
            show_video_bitmap(videoPage[videoPageId]);
            videoPageId++;
            videoPageId %= 2;
            buffer = videoPage[videoPageId];
            break;
        case VIDEO_MODE_DOUBLE_BUFFERING:
            blit(videoPage[0], screen, 0, 0, 0, 0, SCREEN_W, SCREEN_H);
            lastTimeCheck = clock();
            break;
        case VIDEO_MODE_NO_BUFFERING:
            lastTimeCheck = clock();
            break;
    }

    pthread_mutex_unlock(&videoMutex);
}